package com.zhihaoliang.coroutine.buss.flow.func

import com.zhihaoliang.coroutine.util.log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * @author 支豪亮
 * @date 2022/10/26 15:25
 * @des Declarative handling
 */
object FlowDeclarative {
    fun onDeclarative(mainScope: CoroutineScope) = mainScope.launch {
        try {
            simple().collect { value -> log("try : $value") }
        } catch (e:Exception){
            log("try : $e")
        }finally {
            log("try : Done")
        }
        simple()
            .onCompletion { cause ->log("Flow completed exceptionally $cause") }
            .catch { cause -> log("Caught exception: $cause") }.collect { value -> log("catch $value") }

        (1..4).asFlow()
            .onCompletion { cause -> log("asFlow Flow completed with $cause") }
            .catch { cause -> log("asFlow Caught exception: $cause") }
            .collect { value ->
                log("asFlow $value")
            }
    }

    private fun simple(): Flow<Int> = flow {
        emit(1)
        throw RuntimeException()
    }
}